﻿using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using Cubicle.Core.Config;

namespace Cubicle.Core.Processors
{
    public class QueueWrapper<T> : Processor<T>
    {
        private bool _isBuilt = false;
        private readonly ProcessorQueue<T> _queue = new ProcessorQueue<T>();
        private readonly CompositionContainer _container;
        private readonly ProcessorConfig _config;

        [ImportingConstructor]
        public QueueWrapper(CompositionContainer container, EngineConfig config, string contractName)
        {
            var queueConfig = config.Queues.FirstOrDefault(x => x.Key == contractName);
            if (queueConfig == null) 
                throw new Exception(String.Format("Error building queue wrapper. Contract not found '{0}", contractName));
            _container = container;
            _config = queueConfig.ProcessorConfig;
        }

        public ProcessorQueue<T> Queue
        {
            get
            {
                // Delayed building is required to overcome recursive composition - an alternative would be lazy imports of QueueWrapper
                if (!_isBuilt)
                {
                    _queue.Build(_container, _config);
                    _isBuilt = true;
                }
                return _queue;
            }
        }

        public override T Process(T input)
        {
            return Queue.Process(input);
        }
    }
}